import { isExistUsername, isExistPhone, login, giteeLogin,register, sendCode } from '@/api/member/member'
import { setToken, getToken, getName, setName, getPhoto, setPhoto } from "@/utils/login-token"

const state = {
  token: getToken(),
  name: getName(),
  photo: getPhoto()
}

const mutations = {
  // SET_TOKEN: (state, token) => {
  //   setToken(token)
  // }
}

const actions = {
  isExistUsername({ commit }, username) {
    return new Promise((resolve, reject) => {
      isExistUsername(username)
        .then(response => {
          resolve(response)
        }).catch(error => {
          reject(error)
        })
    })
  },
  isExistPhone({ commit }, phone) {
    return new Promise((resolve, reject) => {
      isExistPhone(phone)
        .then(response => {
          resolve(response)
        }).catch(error => {
        reject(error)
      })
    })
  },
  login({ commit }, query) {
    return new Promise((resolve, reject) => {
      login(query)
        .then(response => {
          setToken(response.token)
          setName(response.name)
          setPhoto(response.photo)
          resolve(response)
        }).catch(error => {
        reject(error)
      })
    })
  },
  giteeLogin({ commit }, code) {
    return new Promise((resolve, reject) => {
      giteeLogin(code)
        .then(response => {
          setToken(response.token)
          setName(response.name)
          setPhoto(response.photo)
          resolve(response)
        }).catch(error => {
        reject(error)
      })
    })
  },
  sendCode({ commit }, phone) {
    return new Promise((resolve, reject) => {
      sendCode(phone)
        .then(response => {
          resolve(response)
        }).catch(error => {
        reject(error)
      })
    })
  },
  register({ commit }, query) {
    return new Promise((resolve, reject) => {
      register(query)
        .then(response => {
          resolve(response)
        }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
